package db

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"golang.org/x/crypto/bcrypt"
)

var db *sqlx.DB


// user 结构体
type User struct {
	UserId   int    `db:"user_id"`
	Username string `db:"username"`
	Password string `db:"password"`
}

// Init 初始化数据库
func init() {
	database, err := sqlx.Open("mysql", "golang_chat:123456@tcp(127.0.0.1:3306)/golang_chat")
	if err != nil {
		fmt.Println(err)
		return
	}
	db = database
	err = db.Ping()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("数据库连接成功")
}

// 指针指向db
func GetDB() *sqlx.DB {
    return db
}

// 去数据库查询用户，判断用户是否存在
func CheckUser(username string) bool {
	var user User
	query := "select * from user where username = ?"
	err := db.Get(&user, query, username)
	return err == nil // 查询到用户，返回true
}

// 保存用户到数据库
func CreateUser(username string, password []byte) bool {
	query := "insert into user (username, password) values (?, ?)"
	_, err := db.Exec(query, username, password)
	return err == nil // 保存成功，返回true
}

// 查询用户信息
func GetUser(username string, password []byte) bool {
	var user User
	query := "select * from user where username = ?"
	err := db.Get(&user, query, username)
	if err != nil {
		return false // 查询不到用户，返回false
	} else {
		// 验证密码
		err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
		if err != nil {
			// 密码不匹配
			return false
		} else {
			// 密码匹配
			return true
		}
	}
}
